package com.tsystems.school.jabber.DataBase.DAO;

import com.tsystems.school.jabber.DataBase.Entities.Conference;
import com.tsystems.school.jabber.DataBase.Entities.Message;
import com.tsystems.school.jabber.DataBase.Entities.Server;
import com.tsystems.school.jabber.DataBase.Entities.User;
import org.hibernate.HibernateException;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Kirill
 * Date: 25.08.11
 * Time: 2:57
 * To change this template use File | Settings | File Templates.
 */
public class UserDAO extends GenericDAO<User>{
	public UserDAO(Class<User> type) {
		super(type);
	}

	public boolean isLoginBusy(String login){
		try{
			startTransaction();
			User user = (User) session.createQuery("from User as user where login = ?")
					.setString(0, login).uniqueResult();
			tx.commit();
			if(user != null){
				return true;
			}
		}catch (HibernateException he){
			handleHibernateException(he);
		}
		return false;
	}

	public User getByLogin(String login){
		User user = null;
		try{
			startTransaction();
			user = (User) session.createQuery("from User as user where login = ?")
					.setString(0,login)
					.uniqueResult();
			tx.commit();
		}catch (HibernateException he){
			handleHibernateException(he);
		}
		return user;
	}

	public List<Message> getUndeliveredMessages(User user){
		List<Message> messages = null;
		try{
			startTransaction();
			//Criterion
			for(Conference conf: user.getContacts()){
				//List<Message> msgs = session.createQuery("from Message ") .setP
			}

		}catch (HibernateException he){
			handleHibernateException(he);
		}
		return messages;
	}

	@Override
	public Long create(User user){
		String serverName = "first";
		Long id = null;
		try{
			startTransaction();
			Server thisServer = (Server)session.createQuery("from Server where name = ?")
					.setString(0,serverName)
					.uniqueResult();
			user.setServer(thisServer);
			session.save(user);
			tx.commit();
		} catch (HibernateException he){
			handleHibernateException(he);
		}
		return id;
	}


}
